package portal.monitor.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;

import beans.HttpConfig;
import net.HttpRequest;
import utils.Log4jInit;
import utils.StaticUtil;
import utils.StreamGobbler;

public class MonBaseUtils {

	
	public static void chmod(String filePath) throws IOException {

		Process p = Runtime.getRuntime().exec("chmod 777 " + filePath);

		/* 为"错误输出流"单独开一个线程读取之,否则会造成标准输出流的阻塞 */
		Thread t = new Thread(new StreamGobbler(p.getErrorStream(), "ErrorStream"));
		t.start();

		try {
			p.waitFor();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			p.destroy();
		}
	}
	
	public static String  updateState(String ftpFileUri, String batUri, List<String> result) {
		if (batUri.equals("")) {
			return "";
		}
		if (createFolders(ftpFileUri)) {
			Log4jInit.logger.info("====create folder success==="+batUri);
			if ((!batUri.equals("")) && runBat(batUri)) {
				Log4jInit.logger.info("====runbat success===");
				StaticUtil.deleteFile(batUri);
				result.add(ftpFileUri);
			} else {
			}
		} else {
			
		}
		return null;
	}
	
	/**
	 * run the bat file in batUri
	 *
	 * @param batUri
	 */
	private static boolean runBat(String batUri) {
		boolean result = false;
		if (!HttpConfig.fake) {
			Process p;
			try {
				chmod(batUri);
				// 执行命令
				p = Runtime.getRuntime().exec(batUri);
				// Log4jInit.logger.info("====exec:"+batUri);
				// 取得命令结果的输出流
				InputStream fis = p.getInputStream();
				// 用一个读输出流类去读
				InputStreamReader isr = new InputStreamReader(fis, "gbk");
				// 用缓冲器读行
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				// 直到读完为止
				while ((line = br.readLine()) != null) {
					if (line.equals("upload file success")) {
						result = true;
					}
				}
				File f = new File(batUri);
//				f.delete();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return result;
		} else {
			return true;
		}
	}
	
	private static boolean createFolders(String ftpFileUri) {
		if (!HttpConfig.fake) {
			String targetUri = ftpFileUri.substring(0, ftpFileUri.lastIndexOf("/") + 1);
			String params = "dirpath=" + targetUri + "&isforce=true&token="
					+ ScheUtils.getToken(HttpConfig.userName, HttpConfig.passWord).getMessage();
			JSONObject result = JSONObject.parseObject(HttpRequest.sendGet(HttpConfig.createFtpFolder, params));
			if (result.getString("result").equals("success")) {
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
	}
	
	
	public static String generateScriptFile(String tempDir, String fileUri, String uploadToolUri)
			throws IOException {

		if (fileUri.equals("") || fileUri.equals(null)) {
			return "";
		}

		String command = uploadToolUri + " -m " + HttpConfig.uploadIP + " -l " + fileUri + " -r " + tempDir
				+ " -u -p 6522 -n jhadmin";
		 Log4jInit.logger.info("command::"+command);
		String scriptFileUri = HttpConfig.scriptFileUri;
		File scriptFile = new File(scriptFileUri);
		if (!scriptFile.exists()) {
			scriptFile.mkdirs();
			chmod(scriptFileUri);
		}
		String scriptUri = scriptFileUri + UUID.randomUUID().toString().substring(0, 20) + ".sh";

		File algorithmBatFile = new File(scriptUri);
		FileWriter fw = new FileWriter(algorithmBatFile);
		chmod(scriptUri);
		fw.write(command);
		fw.close();
		return scriptUri;

	}
	
	public static boolean createModeTag(String execType,String IPS){
		
		String tagPath = MonConfig.localBase+"tag_"+execType+"#"+IPS;
		File file = new File(tagPath);
		try {
			if(file.exists()){
				return false;
			}
			boolean b = file.createNewFile();
			MonBaseUtils.chmod(tagPath);
			return b;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	
	public static String getModeTag(){
		
		String tagPath = MonConfig.localBase;
		File dir = new File(tagPath);
		File[] files = dir.listFiles();
		for(File f :files){
			String name = f.getName();
			if(f.isFile()&& name.contains("tag")){
				return f.getAbsolutePath();
			}
		}
		return null;
	}

	public static boolean rmModeTag(String tagPath){
		File f = new File(tagPath);
		if(f.exists()){
			return f.delete();
		}
		return true;
	}
	
	public static boolean copyFile(String oldPath,String newPath){
		
		File f = new File(newPath);
		if(f.exists()) f.delete();
		
		Process p;
		try {
			p = Runtime.getRuntime().exec("cp "+oldPath+" "+newPath);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 创建文件
	 */
	public static File createFile(String cmd,String folder,String fileName){
		
		File PLFile = new File(folder+fileName);
		if(PLFile.exists()){
			PLFile.delete();
		}
		try {
			PLFile.createNewFile();
			MonBaseUtils.chmod(PLFile.getAbsolutePath());
			Writer out1 =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PLFile), "UTF-8"));
			out1.write(cmd);
	    out1.flush();
	    out1.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return PLFile;
	}
}
